// pages/test/test.js
Page({

  data: {
    testItem: {},
    classIcon: 'cloud://test-qhmap.7465-test-qhmap-1301577769/image/icon.jpg',
    classKeys: ["中心名称", "顾问（中文+英文）"],
    classInfo: {},
    userName: '',
    hasInfos: false
  },
  onLoad: function (options) {
    var testItem = JSON.parse(decodeURIComponent(options.testItem))
    console.log(testItem)
    this.setData({
      testItem: testItem
    })
    this.getUserInfo()
  },
  onShareAppMessage: function () {

  },
  //获取个人信息回调
  getUserInfoListener(e) {
    var userInfo = e.detail.userInfo
    console.log(userInfo)
    var classInfo = this.data.classInfo
    classInfo['考生微信'] = userInfo
    this.setData({
      classInfo: classInfo,
      userName: userInfo.nickName
    })
    this.hasInfos()
  },
  //输入监听
  bindKeyInput(e) {
    var key = e.currentTarget.dataset.key
    var value = e.detail.value
    var classInfo = this.data.classInfo
    classInfo[key] = value
    console.log(key, value)
    this.hasInfos()
    this.setData({
      classInfo: classInfo
    })
  },
  //是否已获得所有属性
  hasInfos() {
    var classInfo = this.data.classInfo
    var classKeys = this.data.classKeys
    var classInfoLen = Object.keys(classInfo).length
    var hasInfos = classInfoLen >= classKeys.length + 1
    console.log(classInfoLen)
    this.setData({
      hasInfos: hasInfos
    })
  },
  //点击开始考试按钮
  startTest(e) {
    var hasInfos = this.data.hasInfos
    var classInfo = this.data.classInfo
    var testItem = this.data.testItem
    if (hasInfos) {
      wx.navigateTo({
        url: 'detail/detail?classInfo=' + encodeURIComponent(JSON.stringify(classInfo)) +
          "&testItem=" + encodeURIComponent(JSON.stringify(testItem))
      })
    } else {
      wx.showToast({
        title: '请完善中心信息',
        icon: 'none'
      })
    }
  },
  // 获取个人信息
  getUserInfo: function () {
    wx.getUserInfo({
      success: res => {
        console.log("getUserInfo-success", res)
        var classInfo = this.data.classInfo
        classInfo['考生微信'] = res.userInfo
        this.setData({
          classInfo: classInfo,
          userName: res.userInfo.nickName
        })
        //设置全局的用户信息
        getApp().globalData.userInfo = res.userInfo
      },
      fail: err => {
        console.log("getUserInfo-fail", err)
      }
    })
  }
})